from flask import current_app, abort, render_template, g, request, jsonify

from info import db
from info.constants import CLICK_RANK_MAX_NEWS
from info.models import News, Comment, CommentLike, User
from info.modules.news import news_blu
from info.utils.common import user_login_data
from info.utils.response_code import RET, error_map


# 显示新闻详情
@news_blu.route('/<int:news_id>')
@user_login_data
def get_news_detail(news_id):
    # 从数据库中取出新闻数据
    try:
        news = News.query.get(news_id)
    except BaseException as e:
        current_app.logger.error(e)

    if not news:  # 判断是否有该新闻
        return abort(404)

    # 让点击量加1
    news.clicks += 1

    # 从数据库中取出点击量最多的6条新闻, 进行模板渲染
    rank_list = []  # type: list[News]
    try:
        rank_list = News.query.order_by(News.clicks.desc()).limit(CLICK_RANK_MAX_NEWS).all()
    except BaseException as e:
        current_app.logger.error(e)

    user = g.user
    is_collected = False
    if user:
        # 判断新闻是否被收藏  虽然collection_news设置了dynamic,但是if in会直接查询保存的数据,不需要加all()
        if news in user.collection_news:
            is_collected = True

    # 将该新闻的所有评论数据传到模板中, 进行渲染
    try:
        comments = Comment.query.filter(Comment.news_id == news.id).order_by(Comment.create_time.desc()).all()
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])

    # 查询该新闻的评论中, 哪些被当前用户进行了点赞
    comment_list = []
    for comment in comments:
        comment_dict = comment.to_dict()
        is_comment_like = False
        if user:  # 用户登录的情况
            # 这些评论哪个被该用户点赞
            if comment in user.up_comments:
                is_comment_like = True

        comment_dict["is_comment_like"] = is_comment_like
        comment_list.append(comment_dict)

    is_followed = False
    # 登录状态并且新闻有作者
    if user and news.user:
        # 判断当前用户是否关注了这个作者
        if news.user in user.followed:
            is_followed = True

    user = g.user.to_dict() if g.user else None
    return render_template("news/detail.html", news=news.to_dict(), rank_list=rank_list, user=user, is_collected=is_collected, comments=comment_list, is_followed=is_followed)


# 收藏/取消收藏
@news_blu.route('/news_collect', methods=['POST'])
@user_login_data
def news_collect():
    # 判断用户是否登录
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg=error_map[RET.SESSIONERR])
    
    # 获取参数
    news_id = request.json.get("news_id")
    action = request.json.get("action")
    # 校验参数
    if not all([news_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    try:
        news_id = int(news_id)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    if action not in ["collect", "cancel_collect"]:
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    # 判断新闻是否存在
    try:
        news = News.query.get(news_id)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])
    
    if not news:
        return jsonify(errno=RET.NODATA, errmsg=error_map[RET.NODATA])
    
    if action == "collect":  # 如果收藏, 将该新闻添加到收藏列表中
        
        if news not in user.collection_news:
            user.collection_news.append(news)
            
    else:  # 如果取消收藏, 将该新闻从收藏列表中删除
        if news in user.collection_news:
            user.collection_news.remove(news)
    
    return jsonify(errno=RET.OK, errmsg=error_map[RET.OK])


# 评论新闻
@news_blu.route('/news_comment', methods=['POST'])
@user_login_data
def news_comment():
    # 判断用户是否登录
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg=error_map[RET.SESSIONERR])

    # 获取参数
    comment_content = request.json.get("comment")
    news_id = request.json.get("news_id")
    parent_id = request.json.get("parent_id")
    # 校验参数
    if not all([comment_content, news_id]):
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])
    try:
        news_id = int(news_id)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    # 判断新闻是否存在
    try:
        news = News.query.get(news_id)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])

    if not news:
        return jsonify(errno=RET.NODATA, errmsg=error_map[RET.NODATA])

    # 生成评论模型
    comment = Comment()
    comment.content = comment_content
    comment.user_id = user.id
    comment.news_id = news_id
    if parent_id:
        try:
            comment.parent_id = int(parent_id)
        except BaseException as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    db.session.add(comment)
    try:
        db.session.commit()
    except BaseException as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])

    # 返回响应
    return jsonify(errno=RET.OK, errmsg=error_map[RET.OK], data=comment.to_dict())


# 点赞/取消点赞评论
@news_blu.route('/comment_like', methods=['POST'])
@user_login_data
def comment_like():
    # 判断用户是否登录
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg=error_map[RET.SESSIONERR])
    # 获取参数
    comment_id = request.json.get("comment_id")
    action = request.json.get("action")
    if not all([comment_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])
    if action not in ["add", "remove"]:
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])
    try:
        comment_id = int(comment_id)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])
    # 判断是否有该评论
    try:
        comment = Comment.query.get(comment_id)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])
    
    if not comment:
        return jsonify(errno=RET.NODATA, errmsg=error_map[RET.NODATA])
    try:
        ck = CommentLike.query.filter(CommentLike.user_id == user.id, CommentLike.comment_id == comment_id).first()
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])
    
    # 根据action,进行处理
    if action == "add":
        # 点赞, 生成点赞模型
        if not ck:
            comment_like = CommentLike()
            comment_like.user_id = user.id
            comment_like.comment_id = comment_id
            db.session.add(comment_like)
            # 让点赞数+1
            comment.like_count += 1
    else:
    # 取消点赞, 数据库中删除对应的模型
        if ck:
            db.session.delete(ck)
            comment.like_count -= 1
            
    return jsonify(errno=RET.OK, errmsg=error_map[RET.OK])


# 关注/取消关注
@news_blu.route('/followed_user', methods=['POST'])
@user_login_data
def followed_user():
    # 判断用户是否登录
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg=error_map[RET.SESSIONERR])

    # 获取参数
    user_id = request.json.get("user_id")
    action = request.json.get("action")
    # 校验参数
    if not all([user_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    try:
        user_id = int(user_id)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    if action not in ["follow", "unfollow"]:
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    # 判断作者是否存在
    try:
        author = User.query.get(user_id)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])

    if not author:
        return jsonify(errno=RET.NODATA, errmsg=error_map[RET.NODATA])

    if action == "follow":  # 如果关注, 将该作者添加到关注列表中

        if author not in user.followed:
            user.followed.append(author)

    else:  # 如果取消关注, 将该作者从关注列表中删除
        if author in user.followed:
            user.followed.remove(author)

    return jsonify(errno=RET.OK, errmsg=error_map[RET.OK])



